/*  
* Copyright 2013-2020 Smartdot Technologies Co., Ltd. All rights reserved.  * SMARTDOT PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.  * 
*/ package com.ssm.zhou.service.impl;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ssm.zhou.dao.IUserDao;
import com.ssm.zhou.dto.LoginRespDto;
import com.ssm.zhou.dto.LoginRespUser;
import com.ssm.zhou.dto.LoginUserDto;
import com.ssm.zhou.dto.enums.LoginRespEnum;
import com.ssm.zhou.entity.User;
import com.ssm.zhou.exception.UserException;
import com.ssm.zhou.service.IUserService;
import com.ssm.zhou.utils.CommonUtils;

/** 
 * <p>  
 *   
 * @author <a href="mailto:zhoujb@smartdot.com.cn">周竞博</a>  * @version 1.0, 2020年5月30日 
 */
@Service
public class UserServiceImpl implements IUserService {
	private static Logger logger = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);
	// 注入dao层接口
	@Autowired
	private IUserDao userDao;
	
	@Override
	public void insertUser(User user) {

		try{
			// 测试异常页面
			// System.out.println(10/0);
			System.out.println("-------" + userDao.queryUserByName(user.getUserName()));
			if(userDao.queryUserByName(user.getUserName()) != null) throw new UserException("用户名在数据库中已存在！");
			if( !user.getSex().equals("")  && !user.getSex().equals("男") && !user.getSex().equals("女") ) throw new UserException("性别只能是男或者女！");
			user.setUserId(CommonUtils.uuid());
			System.out.println(user);
			userDao.insertUser(user);
		}catch (UserException e) {
			logger.error(e.getMessage());
			throw new UserException(e.getMessage());
		}catch (Exception e){
			e.printStackTrace();
			logger.error(e.getMessage());
			throw new RuntimeException(e);
		}
	}

	@Override
	public LoginRespDto userLogin(LoginUserDto loginUserDto) {
		
		// TODO Auto-generated method stub
		String userName = loginUserDto.getUsername();
		String password = loginUserDto.getPassword();
		LoginRespUser loginRespUser = new LoginRespUser();
		if(userDao.queryUserByName(userName) == null){
			return new LoginRespDto(LoginRespEnum.USERNAMENOTFIND,null);
		}
		User user = userDao.queryUserByNameAndPassword(userName, password);
		if(user == null) {
			return new LoginRespDto(LoginRespEnum.LOGINIFOERROR,null);
		}
		// 把user的属性拷贝到loginRespUser
		BeanUtils.copyProperties(user,loginRespUser);
		return new LoginRespDto(LoginRespEnum.SUCCESS, loginRespUser);	
		
		//return new LoginRespDto(LoginRespEnum.SUCCESS);		
	}

}
 